package com.hellogood.yaohuo.client.bussiness.ziyou;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.hellogood.yaohuo.client.bussiness.AbstractTab;
import com.hellogood.yaohuo.client.bussiness.FormController;
import com.hellogood.yaohuo.client.common.CommonMessages;
import com.hellogood.yaohuo.client.common.GoodsSearchWindow;
import com.hellogood.yaohuo.client.common.LoginUser;
import com.hellogood.yaohuo.client.common.OrgTextItemTreeClickHandler;
import com.hellogood.yaohuo.client.common.Tools;
import com.hellogood.yaohuo.shared.data.Constants;
import com.hellogood.yaohuo.shared.entity.Detail;
import com.hellogood.yaohuo.shared.entity.Form;
import com.hellogood.yaohuo.shared.entity.Ziyou;
import com.hellogood.yaohuo.shared.entity.ZyDetail;
import com.hellogood.yaohuo.shared.entity.ZyForm;
import com.hellogood.yaohuo.shared.services.CommonService;
import com.hellogood.yaohuo.shared.services.ZiyouService;
import com.hellogood.yaohuo.shared.vo.BasicVo;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.DateDisplayFormat;
import com.smartgwt.client.types.Overflow;
import com.smartgwt.client.types.Positioning;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.CheckboxItem;
import com.smartgwt.client.widgets.form.fields.DateItem;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.IntegerItem;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.StaticTextItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.BlurEvent;
import com.smartgwt.client.widgets.form.fields.events.BlurHandler;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import com.smartgwt.client.widgets.form.fields.events.KeyPressEvent;
import com.smartgwt.client.widgets.form.fields.events.KeyPressHandler;
import com.smartgwt.client.widgets.form.validator.IsIntegerValidator;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.layout.VLayout;

public class ZiyouFormController extends FormController {

	public ZiyouFormController(AbstractTab tab) {
		super(tab);
	}

	public void initView() {
		if(blurOrg!=null){
			blurOrg.removeHandler();
		}
		codeItem = new TextItem("code", "单据号");
		codeItem.setCanEdit(false);
		codeItem.setValue("*");
		pszxItem = new SelectItem("pszx", "配送中心");
		pszxItem.setCanEdit(false);
		orgItem = new TextItem("org", "组织");
		orgItem.setRequired(true);
		orgItem.setCanEdit(false);
		dateItem = new DateItem("date", "日期");
		dateItem.setDateFormatter(DateDisplayFormat.TOJAPANSHORTDATE);
		dateItem.setUseTextField(true);
		dateItem.setCanEdit(false);
		zdUserItem = new TextItem("zdUser", "制单人");
		zdUserItem.setCanEdit(false);
		remarkItem = new TextItem("reamrk", "备注");
		orgItem.addKeyPressHandler(new OrgTextItemTreeClickHandler(orgItem, remarkItem));

		form = new DynamicForm();
		form.setSize("100%", "10%");
		form.setAlign(Alignment.CENTER);
		form.setNumCols(6);
		form.setFields(codeItem, orgItem, dateItem, zdUserItem, remarkItem);
		form.setAutoFocus(true);
		form.setDisabled(true);

		ziyouForm = new DynamicForm();
		ziyouForm.setNumCols(16);
		listGrid = new ListGrid();

		Label titleLabel = new Label();
		titleLabel.setWidth("100%");
		titleLabel.setHeight(40);
		titleLabel.setAlign(Alignment.CENTER);
		titleLabel.setContents("<H2>自由补货单</H2>");

		VLayout gridLayout = new VLayout();
		gridLayout.setOverflow(Overflow.SCROLL);
		gridLayout.setSize("100%", "90%");
		gridLayout.addMember(ziyouForm);
		gridLayout.setShowEdges(true);

		layout = new VLayout();
		layout.setSize("100%", "100%");
		layout.setMembers(titleLabel, form, gridLayout);
		ZiyouService.Util.getInstance().getAllZiyou(new ZiyouGetDataBuildForm(ziyouForm));
		buildFormPrintView();
	}

	@Override
	public void initForm() {
		codeItem.setValue("*");
		orgItem.setValue("");
		orgItem.setDisabled(false);

		codeItem.setDisabled(true);

		dateItem.setDisabled(true);
		zdUserItem.setDisabled(true);

		remarkItem.setValue("");
		remarkItem.setCanEdit(true);
		remarkItem.setDisabled(false);
		Date date = new Date();
		dateItem.setValue(date);
		zdUserItem.setValue(LoginUser.getInstance().getCurrentUser().getStaffCode() + "-" + LoginUser.getInstance().getCurrentUser().getStaffName());
		status = Constants.FORM_STATUS_NEW;
		form.setDisabled(false);
		orgItem.focusInItem();
		orgItem.setCanEdit(true);
		ziyouForm.setDisabled(false);
	}

	public void saveForm() {
		if (form.validate() && ziyouForm != null && ziyouForm.validate()) {
			listGrid.saveAllEdits();

			boolean isModify = false;
			Object billNo = codeItem.getValue();
			if (billNo != null && !billNo.equals("*")) {
				isModify = true;
			}
			msgWindow = new Window();
			msgWindow.setIsModal(true);
			msgWindow.show();
			msgWindow.setWidth(200);
			msgWindow.setHeight(100);
			msgWindow.centerInPage();
			msgWindow.setTitle("提示");
			Label label = new Label();
			label.setWidth(150);
			label.setContents("  正在保存单据，请稍后...");
			label.setAlign(Alignment.CENTER);
			msgWindow.addChild(label);
			if (!isModify) {
				ZiyouService.Util.getInstance().getLastZyBillNo(new SaveAsyncCallback(billNo, isModify));
			} else {
				String saveResult = save(billNo.toString(), isModify);
				if (!saveResult.equals("")) {
					SC.say(saveResult);
				}
			}

		}
	}

	@Override
	public void modifyForm() {
		ziyouForm.setDisabled(false);
	}

	@Override
	public void updateForm(Form form) {
		codeItem.setValue(form.getBillNo());
		codeItem.setCanEdit(false);
		codeItem.setDisabled(true);
		if (form.getShopCode() != null) {
			pszxItem.setValue(form.getOrgCode() + "-" + form.getOrgName());
			pszxItem.setCanEdit(false);
			pszxItem.setDisabled(true);
			orgItem.setValue(form.getShopCode() + "-" + form.getShopName());
			orgItem.setCanEdit(false);
		} else {
			orgItem.setValue(form.getOrgCode() + "-" + form.getOrgName());
			orgItem.setCanEdit(false);
		}
		orgItem.setDisabled(true);

		if (form.getVendorCode() != null) {
			vendorItem.setValue(form.getVendorCode() + "-" + form.getVendorName());
			vendorItem.setCanEdit(false);
			vendorItem.setDisabled(true);
		}
		dateItem.setValue(form.getBillDate());
		dateItem.setCanEdit(false);
		dateItem.setDisabled(true);
		zdUserItem.setValue(form.getStaffCode() + "-" + form.getStaffName());
		zdUserItem.setCanEdit(false);
		zdUserItem.setDisabled(true);
		remarkItem.setValue(form.getRemark());
		remarkItem.setCanEdit(false);
		remarkItem.setDisabled(true);
		List<Detail> list = form.getList();
		Record[] rds = new Record[list.size()];
		FormItem[] zyItems = ziyouForm.getFields();
		for (int i = 0; i < zyItems.length; i += 4) {
			for (int j = 0; j < list.size(); j++) {
				Detail vo = list.get(j);
				Object ziyou = zyItems[i + 1].getTitle();
				if (ziyou != null) {
					String zyCode = ziyou.toString().split("-")[0];
					if (zyCode.equals(vo.getZyCode())) {
						zyItems[i].setValue(true);
						zyItems[i + 2].setValue(vo.getCounts());
						zyItems[i + 3].setValue(vo.getRemark());
						break;
					}
				}
			}
		}

		listGrid.setData(rds);
		FormItem[] items = this.form.getFields();
		if (items != null) {
			for (FormItem item : items) {
				item.setValue(item.getValue());
				item.focusInItem();
			}
		}
		if (form.getRzDate() != null && !form.getRzDate().equals("")) {
			if (items != null) {
				for (FormItem item : items) {
					item.setCanEdit(false);
				}
			}
			tab.showRzSuccessful();
			status = Constants.FORM_STATUS_BANKED;
		} else {
			tab.showSaveSuccessful();
			status = Constants.FORM_STATUS_SAVED;
		}

		fillPrintForm(form);
		printListGrid.setData(rds);
	}

	@Override
	public void cancelForm() {
		isCancelBtnClicked = true;
		
		if (blurOrg != null) {
			orgItem.setValue("-");
			orgItem.blurItem();
		}

		orgItem.setCanEdit(false);
		orgItem.setDisabled(true);
		orgItem.setValue("");
		dateItem.setValue("");
		zdUserItem.setValue("");

		remarkItem.setValue("");
		remarkItem.setDisabled(true);
		ziyouForm.setDisabled(true);

		FormItem[] items = ziyouForm.getFields();
		for (int i = 0; i < items.length; i += 4) {
			items[i].setValue(false);
			items[i + 2].setValue("");
			items[i + 3].setValue("");
		}
	}

	private class SaveAsyncCallback implements AsyncCallback<String> {
		boolean isModify = false;

		public SaveAsyncCallback(Object billNo, boolean isModify) {
			this.isModify = isModify;
		}

		@Override
		public void onFailure(Throwable caught) {
			msgWindow.destroy();
			SC.say(caught.getMessage());
		}

		@Override
		public void onSuccess(String result) {
			String saveResult = save(result.toString(), isModify);
			if (!saveResult.equals("")) {
				SC.say(saveResult);
			}
		}
	}

	public String doSave(String billNo, boolean isModify) {
		// listGrid.cancelEditing();
		ZyForm form = new ZyForm();
		form.setBillNo(billNo);
		form.setBillDate(dateItem.getValue().toString());
		form.setOrgCode(orgItem.getValue() == null ? "" : orgItem.getValue().toString().split("-")[0]);
		form.setOrgName(orgItem.getValue() == null ? "" : orgItem.getValue().toString().split("-")[1]);
		form.setRemark(remarkItem.getValue() == null ? "" : remarkItem.getValue().toString());
		form.setRzDate("");
		form.setStaffCode(zdUserItem.getValue().toString().split("-")[0]);
		form.setTimeMark(Tools.getTodayFormattedDate());
		form.setStaffName(zdUserItem.getValue().toString().split("-")[1]);
		form.setCost(new BigDecimal(0));
		form.setNetCost(new BigDecimal(0));
		form.setTotal(new BigDecimal(0));

		FormItem[] items = ziyouForm.getFields();
		List<Detail> list = new ArrayList<Detail>();
		if (items != null) {
			int totalFormCount = 0;
			for (int i = 0; i < items.length; i += 4) {
				ZyDetail d = new ZyDetail();
				FormItem item = items[i];
				if (item.getValue() != null && item.getValue().equals(true)) {
					d.setBillNo(billNo);
					Object ziyou = items[i + 1].getTitle();
					if (ziyou != null) {
						d.setZyCode(ziyou.toString().split("-")[0]);
					}
					int totalCount = 0;
					Object amount = items[i + 2].getValue();
					if (amount == null || amount.toString().equals("0")) {
						continue;
					} else {
						totalCount = Integer.valueOf(amount.toString());
						d.setCounts(totalCount);
					}
					totalFormCount += totalCount;
					Object remark = items[i + 3].getValue();
					d.setRemark(remark == null ? "" : remark.toString().trim());
					list.add(d);
				}
			}
			form.setCounts(totalFormCount);
			form.setList(list);
			ZiyouService.Util.getInstance().saveForm(form, isModify, new SaveResultAsyncCallback(form.getBillNo()));
		}
		return "";
	}

	private class SaveResultAsyncCallback implements AsyncCallback<String> {
		private String billNo = null;

		public SaveResultAsyncCallback(String billNo) {
			this.billNo = billNo;
		}

		@Override
		public void onFailure(Throwable caught) {
			msgWindow.destroy();
			SC.say(caught.getMessage());
		}

		@Override
		public void onSuccess(String result) {
			msgWindow.destroy();
			if (!result.equals("")) {
				SC.say(result);
			} else {
				SC.say(CommonMessages.SaveSuccess);
				codeItem.setValue(billNo);
				orgItem.setCanEdit(false);
				remarkItem.setCanEdit(false);
				form.setDisabled(true);
				ziyouForm.setDisabled(true);
				tab.showSaveSuccessful();
				ZiyouFormController.this.status = Constants.FORM_STATUS_SAVED;
			}

		}
	}

	private class BasicAsyncCallback implements AsyncCallback<BasicVo> {

		private int row = -1;

		public BasicAsyncCallback(int selectedRow) {
			this.row = selectedRow;
		}

		@Override
		public void onFailure(Throwable caught) {
			SC.say(caught.getMessage());
		}

		@Override
		public void onSuccess(BasicVo result) {
			if (row >= 0) {
				if (result != null) {
					listGrid.setEditValue(row, "pluCode", result.getPluCode());
					listGrid.setEditValue(row, "barCode", result.getBarCode());
					listGrid.setEditValue(row, "pluName", result.getPluName());
					listGrid.setEditValue(row, "dept", result.getDepCode() + "-" + result.getDepName());
					listGrid.setEditValue(row, "type", result.getClsCode() + "-" + result.getClsName());
					listGrid.setEditValue(row, "unit", result.getUnit());
					if (listGrid.getEditedCell(row, "color") == null || listGrid.getEditedCell(row, "color").equals("")) {
						listGrid.setEditValue(row, "color", "0-均色");
					}
					if (listGrid.getEditedCell(row, "size1") == null || listGrid.getEditedCell(row, "size1").equals("")) {
						listGrid.setEditValue(row, "size1", "0");
					}
					if (listGrid.getEditedCell(row, "size2") == null || listGrid.getEditedCell(row, "size2").equals("")) {
						listGrid.setEditValue(row, "size2", "0");
					}
					if (listGrid.getEditedCell(row, "size3") == null || listGrid.getEditedCell(row, "size3").equals("")) {
						listGrid.setEditValue(row, "size3", "0");
					}
					if (listGrid.getEditedCell(row, "size4") == null || listGrid.getEditedCell(row, "size4").equals("")) {
						listGrid.setEditValue(row, "size4", "0");
					}
					if (listGrid.getEditedCell(row, "size5") == null || listGrid.getEditedCell(row, "size5").equals("")) {
						listGrid.setEditValue(row, "size5", "0");
					}
					if (listGrid.getEditedCell(row, "size6") == null || listGrid.getEditedCell(row, "size6").equals("")) {
						listGrid.setEditValue(row, "size6", "0");
					}
					if (listGrid.getEditedCell(row, "size") == null || listGrid.getEditedCell(row, "size").equals("")) {
						listGrid.setEditValue(row, "size", "0");
					}
				} else {
					Object code = listGrid.getEditValue(row, 1);
					if (code == null) {
						code = listGrid.getEditedCell(row, 1);
					}
					if (code != null) {
						if (!GoodsSearchWindow.isOpen) {
							GoodsSearchWindow window = new GoodsSearchWindow(ZiyouFormController.this, listGrid, code.toString());
							window.setPosition(Positioning.RELATIVE);
							window.setIsModal(true);
							window.setSize("500", "500");
							window.show();
							window.centerInPage();
							window.getListGrid().focus();
							if (code.toString().equals("")) {
								window.getKeyItem().focusInItem();
							}
						}
					}
				}
			} else {
				/*
				 * Record r = listGrid.getSelectedRecord(); if (result != null
				 * && r != null) { r.setAttribute("pluCode",
				 * result.getPluCode()); r.setAttribute("barCode",
				 * result.getBarCode()); r.setAttribute("pluName",
				 * result.getPluName()); r.setAttribute("dept",
				 * result.getDepCode() + "-" + result.getDepName());
				 * r.setAttribute("type", result.getClsCode() + "-" +
				 * result.getClsName()); r.setAttribute("unit",
				 * result.getUnit()); r.setAttribute("cup", "无");
				 * r.setAttribute("color", "0"); } else { SC.say("无此条码或编码"); }
				 */
			}
		}
	}

	@Override
	public void fillRowWithBasicVo() {
		int col = listGrid.getEditCol();
		int row = listGrid.getEditRow();

		if (col == 1) {
			Object obj = listGrid.getEditValue(row, col);
			if (obj == null) {
				obj = listGrid.getEditedCell(row, col);
			}

			Object org = orgItem.getValue();
			if (org == null) {
				SC.say(CommonMessages.InputOrgPlease);
				orgItem.setSelectOnFocus(true);
				orgItem.selectValue();
				form.focusInItem("org");
			} else if (obj != null) {
				CommonService.Util.getInstance().getBasicVoByCodeAndOrgCode(obj.toString(), org.toString(), new BasicAsyncCallback(row));
			}
		} else if (col > 7 && col < 15) {
			int amount = 0;
			for (int i = 8; i < 15; i++) {
				Object obj = listGrid.getEditValue(row, i);
				if (obj == null) {
					obj = listGrid.getEditedCell(row, i);
				}
				amount += Tools.toInteger(obj);
			}
			listGrid.setEditValue(row, 15, amount);
		}
	}

	@Override
	public void bankForm() {
		Object code = codeItem.getValue();
		if (code != null) {
			List<String> list = new ArrayList<String>();
			list.add(code.toString());
			ZiyouService.Util.getInstance().bankForm(list, new AsyncCallback<String>() {

				@Override
				public void onSuccess(String result) {
					if (!result.equals("")) {
						SC.say(result);
					} else {
						SC.say(CommonMessages.BankSuccess);
						tab.showRzSuccessful();
						status = Constants.FORM_STATUS_BANKED;
					}
				}

				@Override
				public void onFailure(Throwable caught) {
					SC.say(caught.getMessage());
				}
			});
		}
	}

	@Override
	public void delete(String billNo) {
		ZiyouService.Util.getInstance().deleteForm(billNo, new AsyncCallback<String>() {

			@Override
			public void onFailure(Throwable caught) {
				SC.say(caught.getMessage());
			}

			@Override
			public void onSuccess(String result) {
				if (!result.equals("")) {
					SC.say(result);
				} else {
					listGrid.setData(new Record[0]);
					FormItem[] items = form.getFields();
					if (items != null) {
						for (FormItem item : items) {
							item.setCanEdit(false);
							item.setValue("");
						}
					}
					tab.showRzSuccessful();
					SC.say(CommonMessages.DeleteSuccess);
				}
			}
		});

	}

	@Override
	public VLayout buildFormPrintView() {
		printListGrid = new ListGrid();

		// listGrid.setHeaderHeight(40);
		// listGrid.setDisabled(true);
		printListGrid.setCanEdit(true);
		// listGrid.setSelectOnEdit(true);
		printListGrid.setShowRowNumbers(true);
		// Record[] rds = this.getListGrid().get.getRecords();
		// RecordList rl = this.getListGrid().
		// listGrid.setData(rds);

		Label titleLabel = new Label();
		titleLabel.setWidth("100%");
		titleLabel.setAlign(Alignment.CENTER);
		titleLabel.setContents("<H2>自由补货单</H2>");

		printLayout = new VLayout();
		printLayout.setMembers(titleLabel, printForm, printListGrid);

		return printLayout;

	}

	public class ZiyouGetDataBuildForm implements AsyncCallback<List<Ziyou>> {
		private DynamicForm form = null;

		public ZiyouGetDataBuildForm(DynamicForm ziyouForm) {
			this.form = ziyouForm;
		}

		@Override
		public void onFailure(Throwable caught) {
			SC.say(caught.getMessage());
		}

		@Override
		public void onSuccess(List<Ziyou> zyList) {
			if (zyList != null) {
				IsIntegerValidator isIntegerValidator = new IsIntegerValidator();
				FormItem[] items = new FormItem[zyList.size() * 4];
				for (int i = 0; i < zyList.size(); i++) {
					Ziyou zy = zyList.get(i);
					CheckboxItem checkboxItem = new CheckboxItem("checkbox" + i, "");
					StaticTextItem nameItem = new StaticTextItem("name" + i, zy.getZiyouCode() + "-" + zy.getZiyouName());
					IntegerItem amountItem = new IntegerItem("amount" + i, "数量");
					amountItem.setWidth(40);
					amountItem.setValidators(isIntegerValidator);
					TextItem remarkItem = new TextItem("remark" + i, "备注");
					items[i * 4] = checkboxItem;
					items[i * 4 + 1] = nameItem;
					items[i * 4 + 2] = amountItem;
					items[i * 4 + 3] = remarkItem;
					checkboxItem.addChangedHandler(new ClickCheckBox(checkboxItem, amountItem));
					amountItem.addKeyPressHandler(new JumpToNextItem(remarkItem));
					amountItem.addBlurHandler(new BlurHandler() {

						@Override
						public void onBlur(BlurEvent event) {
							if (!form.validate()) {

							}
						}
					});

				}
				ziyouForm.setFields(items);
				ziyouForm.setDisabled(true);
			}
		}
	};

	public class ClickCheckBox implements ChangedHandler {
		private CheckboxItem check = null;
		private IntegerItem item = null;

		public ClickCheckBox(CheckboxItem check, IntegerItem item) {
			this.check = check;
			this.item = item;
		}

		@Override
		public void onChanged(ChangedEvent event) {
			if (check.getValueAsBoolean()) {
				item.focusInItem();
			}
		}
	}

	public class JumpToNextItem implements KeyPressHandler {
		private TextItem item = null;

		public JumpToNextItem(TextItem item) {
			this.item = item;
		}

		@Override
		public void onKeyPress(KeyPressEvent event) {

			if (event.getKeyName() != null && event.getKeyName().equals("Enter")) {
				item.focusInItem();
			}

		}

	};

}
